// pages/album/post.js
import request from '../../utils/request'
import Datetime from '../../utils/datetime'
import calc from '../../utils/calc'

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    albumId: 0,
    id: 0,
    share: false,
    post: {},
    commentsData: {},
    isComment: false,
    commentText: '',
    commentTo: null,
    showCenterDialog: true,
    rewardData: {
      rewardAmount: 0,
      showCenterDialog: false,
      isEditing: false
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.id,
      albumId: options.albumId,
      share: options.share,
    })
    this.fetchPost()
    this.fetchComments()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let post = this.data.post
    let elem = post.attachments[0]
    let imageUrl = ''
    if (elem.file_type == 0) {
      imageUrl = elem.file
    } else {
      imageUrl = elem.file + '?vframe/png/offset/1'
    }
    return {
      title: post.text,
      path: '/pages/album/post?id=' + post.id + '&albumId=' + this.data.albumId + '&share=true',
      imageUrl: imageUrl
    }
  },

  /*
   * 获取相册详情
   */
  fetchPost: function () {
    let that = this
    let url = app.globalData.apiHost + '/albums/post/' + this.data.id
    request(url, 'GET', app.globalData.loginToken, {}, function (err, data) {
      console.log(data)
      if (!err) {
        let datetime = new Datetime(data.created)
        data.createTime = datetime.getDateStr()
        that.setData({ post: data })
      }
    })
  },

  /*
   * 获取评论列表
   */
  fetchComments: function () {
    let that = this
    let url = app.globalData.apiHost + '/albums/post/' + this.data.id + '/comments/'
    request(url, 'GET', app.globalData.loginToken, {}, function (err, data) {
      console.log(data)
      data.results.reverse()
      if (!err) {
        that.setData({ commentsData: data })
      }
    })
  },

  /*
   * 查看图片大图
   */
  viewImages: function (e) {
    let imgIndex = parseInt(e.currentTarget.dataset.index)
    let post = this.data.post
    let images = []
    let currentImg = ''
    for (let i = 0; i < post.attachments.length; i++) {
      let item = post.attachments[i]
      if (item.file_type == 0) {
        images.push(item.file)
      }
      if (imgIndex == i) {
        currentImg = item.file
      }
    }
    wx.previewImage({
      urls: images,
      current: currentImg
    })
  },

  /*
   * 播放视频
   */
  playVideo: function (e) {
    let videoIndex = parseInt(e.currentTarget.dataset.index)
    let post = this.data.post
    let videoId = 'video_' + videoIndex
    this.videoCtx = wx.createVideoContext(videoId)
    this.videoCtx.play()
    this.videoCtx.requestFullScreen()
  },

  /*
   * 分享
   */
  sharePost: function(e) {

  },

  /*
   * 写评论
   * 设置一个固定的input，一旦开始编辑，就让他的focus为true
   */
  writeComment: function (e) {
    // 设置评论输入状态
    this.setData({
      isComment: true
    })
  },

  /*
   * 回复评论
   */
  replyComment: function (e) {
    let toIndex = parseInt(e.currentTarget.dataset.toindex)
    let post = this.data.post
    let commentsData = this.data.commentsData
    let commentTo = commentsData.results[toIndex]
    let that = this
    if (app.globalData.account.id == commentTo.author.id) {
      // 提示用户删除评论
      wx.showActionSheet({
        itemList: ['删除评论'],
        success: function (res) {
          if (!res.tapIndex) {
            let data = { id: commentTo.id }
            let url = app.globalData.apiHost + '/albums/comments/' + commentTo.id + '/delete/'
            request(url, 'DELETE', app.globalData.loginToken, data, function (err, data) {
              if (!err) {
                // 删除成功
                commentsData.count --
                commentsData.results.splice(toIndex, 1)
                that.setData({ commentsData: commentsData })
              }
            })
          }
        }
      })
    } else {
      this.setData({
        isComment: true,
        commentTo: commentTo,
      })
    }

  },

  /*
   * 放弃评论
   */
  giveupComment: function (e) {
    this.setData({
      isComment: false,
      commentText: '',
      commentTo: null
    })
  },

  /*
   * 评论编辑了
   */
  commentTextChange: function (e) {
    this.setData({
      commentText: e.detail.value
    })
  },

  /*
   * 发评论
   */
  sendComment: function (e) {
    let text = this.data.commentText
    let post = this.data.post
    let commentsData = this.data.commentsData
    this.setData({
      isComment: false,
      commentText: '',
    })
    let that = this
    let data = {
      post: post.id,
      author: app.globalData.account.id,
      text: text
    }
    if (this.data.commentTo) {
      data.to = this.data.commentTo.id
    }
    let url = app.globalData.apiHost + '/albums/post/' + post.id + '/comments/'
    request(url, 'POST', app.globalData.loginToken, data, function (err, data) {
      if (!err) {
        console.log(data)
        // 创建成功，添加到评论列表
        commentsData.results.push(data)
        commentsData.count ++
        that.setData({ commentsData: commentsData, commentTo: null })
      }
    })
  },

  /*
   * 取消评论
   */
  cancelComment: function (e) {
    this.setData({
      isComment: false,
      commentText: '',
      commentTo: null
    })
  },

  /******************* 打赏相关 **********************/
  /*
   * 打赏照片的对话框
   */
  rewardDialog: function (e) {
    let rewardAmount = calc.getRandomNum(0.1, 20)
    this.setData({
      rewardData: {
        showCenterDialog: true,
        rewardAmount: rewardAmount,
        isEditing: false
      }
    })
  },

  /*
   * 取消打赏
   */
  closeReward: function (e) {
    this.setData({
      rewardData: {
        showCenterDialog: false,
        rewardAmount: 0,
        isEditing: false,
      }
    })
  },

  /*
   * 刷新打赏金额
   */
  refreshReward: function (e) {
    let rewardData = this.data.rewardData
    let rewardAmount = calc.getRandomNum(0.1, 20)
    rewardData.rewardAmount = rewardAmount
    this.setData({
      rewardData: rewardData
    })
  },

  /*
   * 确认打赏
   */
  confirmReward: function (e) {
    let rewardData = this.data.rewardData
    let rewardAmount = rewardData.rewardAmount
    if (isNaN(rewardAmount)) {
      return wx.showToast({
        title: '请输入数字',
        image: '/images/icon/icon_attention.png'
      })
    }
    if (rewardAmount > 200) {
      return wx.showToast({
        title: '打赏金额不能超过200',
        image: '/images/icon/icon_attention.png'
      })
    }
    wx.showLoading({
      title: '请求中...',
      mask: true
    })
    let post = this.data.post
    let that = this
    let signData = {
      album: this.data.albumId,
      post: post.id,
      fee: rewardAmount * 100
    }
    let signUrl = app.globalData.apiHost + '/pay/get_wechat_prepay_id/'
    // 需要请求后台获取签名
    request(signUrl, 'post', app.globalData.loginToken, signData, function (err, data) {
      wx.hideLoading()
      if (!err) {
        let timeStamp = data.timeStamp.toString()
        wx.requestPayment({
          'timeStamp': timeStamp,
          'nonceStr': data.nonceStr,
          'package': data.package,
          'signType': data.signType,
          'paySign': data.paySign,
          success: function (res) {
            // 支付成功
            rewardData = {
              showCenterDialog: false,
              rewardAmount: 0,
              isEditing: false,
            }
            post.is_bought = true
            app.globalData.needRefresh = true
            that.setData({ post: post })
            wx.showToast({
              title: '打赏成功',
            })
          },
          fail: function (res) {
            console.log(res)
          }
        })
      }
    })
  },

  /*
   * 编辑打赏金额
   */
  editAmount: function (e) {
    let rewardData = this.data.rewardData
    rewardData.isEditing = true
    this.setData({ rewardData: rewardData })
  },

  rewardAmountChange: function (e) {
    let rewardData = this.data.rewardData
    rewardData.rewardAmount = e.detail.value
    this.setData({ rewardData: rewardData })
  },

  endEditAmount: function (e) {
    let rewardData = this.data.rewardData
    rewardData.isEditing = false
    this.setData({ rewardData: rewardData })
  },
  
})